package com.hrbxlh.actionImpl;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.hrbxlh.action.ExcelTest;
import com.hrbxlh.action.ITextWord;
import com.hrbxlh.util.*;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.StringUtil;
import org.omg.CORBA.OBJ_ADAPTER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hrbxlh.dao.CourseDao;
import com.hrbxlh.dao.MyCourseDao;
import com.hrbxlh.dao.QuestionDao;
import com.hrbxlh.dao.RelStuClassDao;
import com.hrbxlh.dao.RelationDao;
import com.hrbxlh.dao.SourceDao;

@Component("questionActionImpl")
@Transactional
public class QuestionActionImpl {

	@Resource(name="questionDao")
	private QuestionDao questionDao;

	@Resource(name="courseDao")
	private CourseDao courseDao;

	@Resource(name="myCourseDao")
	private MyCourseDao myCourseDao;

	@Resource(name = "relStuClassDao")
	private RelStuClassDao relStuClassDao;

	@Resource(name = "relationDao")
	private RelationDao relationDao;

	@Resource(name="sourceDao")
	private SourceDao sourceDao;

	@Autowired
	@Qualifier("sourceActionImpl")
	private SourceActionImpl sourceActionImpl;

	//日志信息
	Logger logger = Logger.getLogger(QuestionActionImpl.class.getName());

	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  题库列表页面。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	public Map<String, Object> getAllQuestionList(Map<String, Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		Map<String, Object> titleMap = new HashMap<String, Object>();
		try {

			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			returnMap.put("stuorteaId", stuorteaId);
			paramMap.put("stuorteaId", stuorteaId);
			//通过教师号获取此教师所属课程
//			List<Map<String,Object>> courseList = courseDao.getTeaTeachCourse(paramMap);
			//20171030 商莹改  通过教师号获取此教师所属课程（教的）
			List<Map<String,Object>> courseList = courseDao.getTeaOwenCourse(paramMap);
			returnMap.put("courseList", courseList);
			//1027xzx修改
			paramMap.put("courseList", courseList);
			//1027xzx修改结束
			/*

			if(courseList!=null&&courseList.size()!=0){
				returnMap.put("courseList", courseList);
				paramMap.put("courseList", courseList);
				System.out.println("最后的map"+paramMap);
				//查询题库列表
				List<Map<String, Object>> questionList = questionDao.getAllQuestionList(paramMap);
				returnMap.put("questionList", questionList);
				returnMap.put("pageNow", pageNow);
				//获取全部页数
				paramMap.put("pageNow", 0);
				List<Map<String, Object>> allMemberList = questionDao.getAllQuestionList(paramMap);
				int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
				returnMap.put("totalPage", totalPage);
				returnMap.put("flag", "success");
			}else{
				//说明此教师没有课程
				returnMap.put("flag", "error");
				returnMap.put("errMsg", "因此教师没有课程所以题库为空");
			}
			*/
			//查询所有课程
//			List<Map<String,Object>> courseListAll = courseDao.getAllCourse();
//			returnMap.put("courseListAll", courseListAll);
			if(courseList!=null&&courseList.size()!=0){
				//查询题库列表
				List<Map<String, Object>> questionList = questionDao.getAllQuestionList(paramMap);
				returnMap.put("questionList", questionList);
				returnMap.put("pageNow", pageNow);
				//获取全部页数
				paramMap.put("pageNow", 0);
				List<Map<String, Object>> allMemberList = questionDao.getAllQuestionList(paramMap);
				int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
				returnMap.put("totalPage", totalPage);
			}else{
				returnMap.put("questionList", null);
				returnMap.put("pageNow", pageNow);
				returnMap.put("totalPage", 0);
			}

			returnMap.put("flag", "success");
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  题库列表页面。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	public Map<String, Object> getAllQuestionListExcel(Map<String, Object> paramMap,HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		Map<String, Object> titleMap = new HashMap<String, Object>();
		try {

			//获取分页数据
			int optionPageNow = Integer.valueOf(String.valueOf(paramMap.get("optionPageNow")));
			int optionPageSize = Integer.valueOf(String.valueOf(paramMap.get("optionPageSize")));
			int judgePageNow = Integer.valueOf(String.valueOf(paramMap.get("judgePageNow")));
			int judgePSize = Integer.valueOf(String.valueOf(paramMap.get("judgePSize")));
			int blanksPageNow = Integer.valueOf(String.valueOf(paramMap.get("blanksPageNow")));
			int blanksPageSize = Integer.valueOf(String.valueOf(paramMap.get("blanksPageSize")));
			int answerPageNow = Integer.valueOf(String.valueOf(paramMap.get("answerPageNow")));
			int answerPageSize = Integer.valueOf(String.valueOf(paramMap.get("answerPageSize")));
			int manyOptionPageNow = Integer.valueOf(String.valueOf(paramMap.get("manyOptionPageNow")));
			int manyOptionPageSize = Integer.valueOf(String.valueOf(paramMap.get("manyOptionPageSize")));
			paramMap.put("optionPageSize", optionPageSize);
			paramMap.put("manyOptionPageSize", manyOptionPageSize);
			paramMap.put("judgePSize", judgePSize);
			paramMap.put("blanksPageSize", blanksPageSize);
			paramMap.put("answerPageSize", answerPageSize);

			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId")) ;
			returnMap.put("stuorteaId", stuorteaId);
			paramMap.put("stuorteaId", stuorteaId);
			logger.info("最后的map"+paramMap);
			//通过课程号获取课程信息
			Map<String,Object> courseMap = courseDao.getCourseDetailById(paramMap);
			returnMap.put("courseMap", courseMap);
			//单选选择集合
			List<Map<String, Object>> optionList = new ArrayList<Map<String, Object>>();
			optionList =questionDao.getOptionQuestionListExcel(paramMap);
			if(optionList.size()!=0) {
				titleMap.put("optionTitle", "单项选择题");
			}
			returnMap.put("optionList", optionList);

			//多选选择集合
			List<Map<String, Object>> manyOptionList = new ArrayList<Map<String, Object>>();
			manyOptionList =questionDao.getManyOptionQuestionListExcel(paramMap);
			if(manyOptionList.size()!=0) {
				titleMap.put("manyOptionTitle", "多项选择题");
			}
			returnMap.put("manyOptionList", manyOptionList);
			//判断集合
			List<Map<String, Object>> judgeList = new ArrayList<Map<String, Object>>();
			judgeList =questionDao.getJudgeQuestionListExcel(paramMap);
			if(judgeList.size()!=0){
				titleMap.put("judgeTitle", "判断题");
			}
			returnMap.put("judgeList", judgeList);
			//填空集合
			List<Map<String, Object>> blanksList = new ArrayList<Map<String, Object>>();
			blanksList =questionDao.getBlanksQuestionListExcel(paramMap);
			if(blanksList.size()!=0){
				titleMap.put("blanksTitle", "填空题");
			}
			returnMap.put("blanksList", blanksList);
			//简答集合
			List<Map<String, Object>> answerList = new ArrayList<Map<String, Object>>();
			answerList =questionDao.getAnswerQuestionListExcel(paramMap);
			if(answerList.size()!=0){
				titleMap.put("answerTitle", "简答题");
			}
			returnMap.put("answerList", answerList);
			returnMap.put("titleMap", titleMap);
			logger.info("最后查到的结果"+returnMap);

		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  查询所选试题类型题库中是否存在
	 * @throws IOException
	 */
	public Map<String, Object> getQuestionsByExcel(Map<String, Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		Map<String, Object> titleMap = new HashMap<String, Object>();
		try {

			String errMsg = "";
			String str = "";
			int mark = 0;
			String finStr = "";
			//获取分页数据
			int optionPageNow = Integer.valueOf(String.valueOf(paramMap.get("optionPageNow")));
			int optionPageSize = Integer.valueOf(String.valueOf(paramMap.get("optionPageSize")));
			int manyOptionPageNow = Integer.valueOf(String.valueOf(paramMap.get("manyOptionPageNow")));
			int manyOptionPageSize = Integer.valueOf(String.valueOf(paramMap.get("manyOptionPageSize")));
			int judgePageNow = Integer.valueOf(String.valueOf(paramMap.get("judgePageNow")));
			int judgePSize = Integer.valueOf(String.valueOf(paramMap.get("judgePSize")));
			int blanksPageNow = Integer.valueOf(String.valueOf(paramMap.get("blanksPageNow")));
			int blanksPageSize = Integer.valueOf(String.valueOf(paramMap.get("blanksPageSize")));
			int answerPageNow = Integer.valueOf(String.valueOf(paramMap.get("answerPageNow")));
			int answerPageSize = Integer.valueOf(String.valueOf(paramMap.get("answerPageSize")));
			paramMap.put("optionPageSize", optionPageSize);
			paramMap.put("manyOptionPageSize", manyOptionPageSize);
			paramMap.put("judgePSize", judgePSize);
			paramMap.put("blanksPageSize", blanksPageSize);
			paramMap.put("answerPageSize", answerPageSize);

			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			returnMap.put("stuorteaId", stuorteaId);
			paramMap.put("stuorteaId", stuorteaId);

			logger.info("最后的map"+paramMap);
			List<Map<String, Object>> optionList = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> manyOptionList = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> judgeList = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> blanksList = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> answerList = new ArrayList<Map<String, Object>>();
			Map<String, Object> listMap = getListMap(paramMap);
			//单选选择集合
			optionList = (List<Map<String, Object>>) listMap.get("optionList");
			if(optionList.size()!=0){
				titleMap.put("optionTitle", "单选选择题");
			}
			returnMap.put("optionList", optionList);
			//多选
			manyOptionList =(List<Map<String, Object>>) listMap.get("manyOptionList");
			if(manyOptionList.size()!=0){
				titleMap.put("manyOptionTitle", "多选选择题");
			}
			returnMap.put("manyOptionList", manyOptionList);
			returnMap.put("manyOptionPageSize", manyOptionPageSize);
			//判断集合
			judgeList =(List<Map<String, Object>>) listMap.get("judgeList");
			if(judgeList.size()!=0){
				titleMap.put("judgeTitle", "判断题");
			}
			returnMap.put("judgeList", judgeList);
			//填空集合
			blanksList =(List<Map<String, Object>>) listMap.get("blanksList");
			if(blanksList.size()!=0){
				titleMap.put("blanksTitle", "填空题");
			}
			returnMap.put("blanksList", blanksList);
			//简答集合
			answerList =(List<Map<String, Object>>) listMap.get("answerList");
			if(answerList.size()!=0){
				titleMap.put("answerTitle", "简答题");
			}
			returnMap.put("answerList", answerList);
			logger.info("optionList"+optionList+"judgeList"+judgeList+"blanksList"+blanksList+"answerList"+answerList+"optionList长度"+optionList.size()+"manyOptionList长度"+manyOptionList.size());
			boolean opFlag=false;
			boolean manyOpFlag=false;
			boolean juFlag=false;
			boolean blFlag=false;
			boolean anFlag=false;
			if(optionList==null||optionList.size()==0||manyOptionList==null||manyOptionList.size()==0||judgeList==null||judgeList.size()==0||blanksList==null||blanksList.size()==0||answerList==null||answerList.size()==0){
				if((optionList==null||optionList.size()==0)&&optionPageSize!=0){
					logger.info("单选选择题没有");
					opFlag = true;
					errMsg = "、单选选择题";
					if(manyOptionPageSize==0&&answerPageSize==0&&judgePSize==0&&blanksPageSize==0){
						mark = 1;
					}
				}if((manyOptionList==null||manyOptionList.size()==0)&&manyOptionPageSize!=0){
					logger.info("多选选择题没有");
					manyOpFlag = true;
					errMsg = errMsg+"、多选选择题";
					if(optionPageSize==0&&answerPageSize==0&&judgePSize==0&&blanksPageSize==0){
						mark = 1;
					}
				}if((judgeList==null||judgeList.size()==0)&&judgePSize!=0){
					logger.info("判断题没有");
					juFlag = true;
					errMsg=errMsg+"、判断题";
					if(optionPageSize==0&&answerPageSize==0&&manyOptionPageSize==0&&blanksPageSize==0){
						mark = 1;
					}
				}if((blanksList==null||blanksList.size()==0)&&blanksPageSize!=0){
					logger.info("填空题没有");
					blFlag = true;
					errMsg=errMsg+"、填空题";
					if(optionPageSize==0&&answerPageSize==0&&judgePSize==0&&manyOptionPageSize==0){
						mark = 1;
					}
				}if((answerList==null||answerList.size()==0)&&answerPageSize!=0){
					logger.info("简答题没有");
					anFlag = true;
					errMsg=errMsg+"、简答题";
					if(optionPageSize==0&&manyOptionPageSize==0&&judgePSize==0&&blanksPageSize==0){
						mark = 1;
					}
				}

				if(!(errMsg.equals(null))&&!(errMsg.equals(""))){
					logger.info("errMsg不为空");
					str = PubMethods.getCharStr(errMsg);
					str = "当前题库没有"+str;
				}
				logger.info("str"+str+"opFlag"+opFlag+"errMsg"+errMsg+"juFlag"+juFlag+"manyOpFlag"+manyOpFlag);
				if(opFlag&&juFlag&&blFlag&&anFlag&&manyOpFlag){
					logger.info("当前题库中没有试题");
					returnMap.put("finalflag", "fail");
					returnMap.put("result", "fail");
					mark = 1;
				}else{
					if(juFlag&&judgeList.size()!=0){
						mark = 1;
					}if(!juFlag&&judgeList.size()!=0){
						mark = 0;
					}if(manyOpFlag&&manyOptionList.size()!=0){
						mark = 1;
					}if(!manyOpFlag&&manyOptionList.size()!=0){
						mark = 0;
					}if(opFlag&&optionList.size()!=0){
						mark = 1;
					}if(!opFlag&&optionList.size()!=0){
						mark = 0;
					}if(anFlag&&answerList.size()!=0){
						mark = 1;
					}if(!anFlag&&answerList.size()!=0){
						mark = 0;
					}
					logger.info("说明有的题有有的题没有");
					returnMap.put("finalflag", "success");
					returnMap.put("result", "fail");
				}
			}else{
				logger.info("说明所有题都有");
				returnMap.put("result", "success");
				returnMap.put("finalflag", "success");
			}
			//判断各种题型是否数量符合
			String errMsg1 = "";
			errMsg1 = questionStr(optionList,manyOptionList,judgeList,blanksList,answerList,optionPageSize,manyOptionPageSize,judgePSize,blanksPageSize,answerPageSize);
			//判断要生成或预览的试题返回的结果
			finStr = questionStr1(errMsg1,str,returnMap);
			returnMap.put("errMsg", finStr);
			returnMap.put("mark", mark);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	private Map<String,Object> getListMap (Map<String,Object> paramMap){
		Map<String,Object> listMap = new HashMap<>();
		List<Map<String, Object>> optionList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> manyOptionList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> judgeList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> blanksList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> answerList = new ArrayList<Map<String, Object>>();
		try {
			//单选选择集合
			optionList =questionDao.getOptionQuestionListExcel(paramMap);
			//多选
			manyOptionList =questionDao.getManyOptionQuestionListExcel(paramMap);
			//判断集合
			judgeList =questionDao.getJudgeQuestionListExcel(paramMap);
			//填空集合
			blanksList =questionDao.getBlanksQuestionListExcel(paramMap);
			//简答集合
			answerList =questionDao.getAnswerQuestionListExcel(paramMap);
			listMap.put("optionList",optionList);
			listMap.put("manyOptionList",manyOptionList);
			listMap.put("judgeList",judgeList);
			listMap.put("blanksList",blanksList);
			listMap.put("answerList",answerList);
		}catch (Exception e){
			e.printStackTrace();
		}
		return listMap;
	}


	/**
	 * 判断各种题型是否数量符合
	 */
	public String questionStr(List<Map<String, Object>> optionList,List<Map<String, Object>> manyOptionList,List<Map<String, Object>> judgeList, List<Map<String, Object>> blanksList,List<Map<String, Object>> answerList
			,int optionPageSize,int manyOptionPageSize,int judgePSize,int blanksPageSize,int answerPageSize){
		String errMsg1 = "";
		if(optionList!= null) {
			if(optionList.size()< optionPageSize && optionPageSize != 0&&optionList.size()!=0) {
				errMsg1 += "、单选选择题";
			}
		}
		if(manyOptionList!= null) {
			if(manyOptionList.size()< manyOptionPageSize && manyOptionPageSize != 0&&manyOptionList.size()!=0) {
				errMsg1 += "、多选选择题";
			}
		}
		if(judgeList!= null) {
			if(judgeList.size()< judgePSize && judgePSize != 0&&judgeList.size()!=0) {
				errMsg1 += "、判断题";
			}
		}
		if(blanksList!= null) {
			if(blanksList.size()< blanksPageSize && blanksPageSize != 0&&blanksList.size()!=0) {
				errMsg1 += "、填空题";
			}
		}
		if(answerList!= null) {
			if(answerList.size()< answerPageSize && answerPageSize != 0&&answerList.size()!=0) {
				errMsg1 += "、简答题";
			}
		}
		errMsg1 = PubMethods.getCharStr(errMsg1);
		return errMsg1;
	}

	/**
	 * 判断要生成或预览的试题返回的结果
	 */
	public String questionStr1(String errMsg1,String str,Map<String,Object> map){
		String countStr = "";
		String finStr = "";
		if(!errMsg1.equals("")&&str.equals("")){
			countStr = "当前题库中" + errMsg1 + "的数量小于输入的数量";
		}
		if(!str.equals("")&&!errMsg1.equals("")&&String.valueOf(map.get("finalflag")).equals("success")&&String.valueOf(map.get("result")).equals("fail")){
			finStr = str + "且" + errMsg1 + "的数量小于输入的数量";
		}
		if(!str.equals("")&&countStr.equals("")&&finStr.equals("")){
			finStr = str;
		}
		if(str.equals("")&&!countStr.equals("")&&finStr.equals("")){
			finStr = countStr;
		}
		return finStr;
	}

	/**
	 * 添加/编辑问题表单提交。
	 * @throws IOException
	 */
	public Map<String,Object> addQuestion(Map<String,Object> paramMap) throws Exception {

		boolean flag = false;
		int questionType=0;
		Map<String,Object> returnMap = new HashMap<String, Object>();
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		String msg = "";
		try {
//			//将题目类型转换
//			if(paramMap.get("type").equals("选择")){
//				questionType=1;
//			}if(paramMap.get("type").equals("判断")){
//				questionType=2;
//			}if(paramMap.get("type").equals("填空")){
//				questionType=3;
//			}if(paramMap.get("type").equals("简答")){
//				questionType=4;
//			}
//			paramMap.put("questionType", questionType);
			String optionMsg = (String) paramMap.get("optionMsg");;
			String ansquesContent = (String) paramMap.get("ansquesContent");
			/*boolean isBracketsFalge = PubMethods.isBrackets(paramMap);
			if(!isBracketsFalge){
				msg = paramMap.get("questionName")+"试题格式输入不正确";
				returnMap.put("flag",false);
				returnMap.put("msg",msg);
				return returnMap;
			}*/
			if(!(String.valueOf(paramMap.get("optionMsg")).equals(null))&&!(String.valueOf(paramMap.get("optionMsg")).equals(""))){
				optionMsg = optionMsg.replaceAll("\n", "<br>");
				optionMsg = optionMsg.replaceAll("\r", "<br>");
				paramMap.put("optionMsg", optionMsg);
			}
			if(!(String.valueOf(paramMap.get("ansquesContent")).equals(null))&&!(String.valueOf(paramMap.get("ansquesContent")).equals(""))){
				ansquesContent = ansquesContent.replaceAll("\n", "<br>");
				ansquesContent = ansquesContent.replaceAll("\r", "<br>");
				paramMap.put("ansquesContent", ansquesContent);
			}
			//通过questionName查询数据库是否应经存在此试题
			List<Map<String,Object>> questionMap = questionDao.getQuestionByName(paramMap);
			if(questionMap!=null&&questionMap.size()!=0){
				returnMap.put("flag", false);
				returnMap.put("msg", "题目重复，添加失败");
				return returnMap;
			}
			if(String.valueOf(paramMap.get("questionName")).length()>500){
				returnMap.put("flag", false);
				returnMap.put("msg", "题目字数超出限制，添加失败");
				return returnMap;
			}
			list.add(paramMap);
			if((Integer)paramMap.get("operationType")==1){
				//添加
				flag = questionDao.addQuestion(list);
			}else{
				//编辑
				flag = questionDao.saveQuestion(paramMap);
			}
			returnMap.put("flag",flag);
			returnMap.put("msg",msg);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * @description  删除题库,传回题库id集合。List<String>形式   jsonStr = ["1","2","3"...]。
	 * @param .List<Integer> paramList 题库id集合
	 * @return boolean (true 成功 ,false失败)
	 * @throws Exception
	 */
	public boolean delQuestions(List<String> paramList) throws Exception {

		boolean resultFlag = false;
		try {
			//删除题库
			resultFlag = questionDao.delQuestions(paramList);

		} catch (Exception e) {
			throw e;
		}
		return resultFlag;
	}

	/**
	 * @description  删除试卷,传回试卷id集合。List<String>形式   jsonStr = ["1","2","3"...]。
	 * @param
	 * @return boolean (true 成功 ,false失败)
	 * @throws Exception
	 */
	@Transactional
	public Map<String,Object> delOnlineQuestion(List<String> paramList) throws Exception {

		boolean resultFlag = false;
		String msg = "";
		Map<String,Object> returnMap = new HashMap<String, Object>();
		FileUpload fileUpload = new FileUpload();
		try {
			//通过试卷主键id查询试卷文件名
			List<Map<String,Object>> questionList = questionDao.getAllFileNameListById(paramList);
			//查询要删除的试卷是否有学生已经答题
//			List<Map<String,Object>> list = questionDao.getStuAnswerByOnIdList(paramList);
			double mincha = PubMethods.surplusTime(String.valueOf(questionList.get(0).get("starttime")));
			double examtime = Integer.valueOf(String.valueOf(questionList.get(0).get("examtime")));
			if((mincha<=examtime)&&Integer.parseInt(String.valueOf(questionList.get(0).get("examState")))==1){
				//是考试的状态并且没到考试时间
				resultFlag = false;
				msg = "学生正在答题，不可删除试卷";
				returnMap.put("resultFlag",resultFlag);
				returnMap.put("msg",msg);
				return returnMap;
			}

			String[] keysArray = {"tomcatUrl", "project_name","server_address"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			//判断文件夹存不存在,不存在就创建
			String filePath = (String)urlmap.get("tomcatUrl")+(String)urlmap.get("project_name")+"upload/question/";
			for (Map<String,Object> questionMap:questionList) {
				//将服务器上的文件删除
				String fileName = String.valueOf(questionMap.get("fileName"));
				resultFlag = fileUpload.deleteFileOnly(filePath,fileName);
			}
			if(resultFlag){
				//查询要删除试卷对应的复制试卷集合
				Map<String,Object> paramMap = new HashMap<>();
				paramMap.put("onlineMark",1);//标识用哪个sql
				paramMap.put("paramList",paramList);
				List<Map<String,Object>> onlineList = questionDao.getAllCopyQuIdList(paramMap);
				//删除试卷对应学生答题数据
				resultFlag = questionDao.delStuanswerByOnlineQuestion(onlineList);
				//删除re_online_class表
				resultFlag = questionDao.delReOnlineClassQuestion(onlineList);
				//删除试卷
				resultFlag = questionDao.delOnlineQuestion(onlineList);
			}
			returnMap.put("resultFlag",resultFlag);
			returnMap.put("msg",msg);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/*
	 * 导入
	 */
	public Map<String,Object> imQuestion(String file, HttpServletRequest request) throws Exception{
		//得到表格中所有的数据
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
		String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
		resultMap = this.getAllByExcel(file,stuorteaId);
		List<Map<String, Object>> listExcel= (List<Map<String, Object>>) resultMap.get("list");
		logger.info("imQuestion得到表格中所有的数据"+listExcel);
		Map<String,Object> returnMap = new HashMap<String,Object>();
		if(listExcel!=null&&listExcel.size()!=0){
			boolean flag1 = questionDao.addQuestion(listExcel);
			if(flag1){
				returnMap.put("result", "success");
				returnMap.put("errMsg", "导入成功");
			}else{
				returnMap.put("result", "fail");
				returnMap.put("errMsg", "填写数据不正确，导入失败");
			}
		}else{
			returnMap.put("result", "fail");
			returnMap.put("errMsg", resultMap.get("errMsg"));
		}
		return returnMap;
	}

	/**
	 * 查询指定目录中电子表格中所有的数据
	 * @param file 文件完整路径 ,stuorteaId教师id
	 * @return
	 */
	public  Map<String, Object> getAllByExcel(String file,String stuorteaId){
		List<Map<String, Object>> list=new ArrayList<Map<String, Object>>();
		Map<String, Object> returnMap = new HashMap<String,Object>();
		try {
			Workbook rwb = Workbook.getWorkbook(new File(file));
			Sheet rs = rwb.getSheet(0);
			int clos = rs.getColumns();//得到所有的列
			int rows = rs.getRows();//得到所有的行
			int questionType = 0;
			logger.info(clos + " rows:" + rows);
			List<String> arr1 = new ArrayList<String>();
			List<String> arr2 = new ArrayList<String>();
			//判断模板是否正确
			for (int j = 0; j < 6; j++){
				arr1.add(rs.getCell(j++, 1).getContents().trim());
				arr1.add(rs.getCell(j++, 1).getContents().trim());
				arr1.add(rs.getCell(j++, 1).getContents().trim());
				arr1.add(rs.getCell(j++, 1).getContents().trim());
				arr1.add(rs.getCell(j++, 1).getContents().trim());
				arr1.add(rs.getCell(j++, 1).getContents().trim());

				arr2.add("编号");
				arr2.add("题目");
				arr2.add("题型");
				arr2.add("选项");
				arr2.add("答案");
				arr2.add("题目所属课程");
			}
			//判断模板是否正确
			returnMap = PubMethods.isModel(arr1,arr2,rs);
			if(returnMap.size()!=0){
				return returnMap;
			}
			int newRow = PubMethods.getNewRows(rows, rs);
			if (newRow == 2) {
				//说明没有数据
				returnMap.put("list", null);
				returnMap.put("errMsg", "数据为空，导入失败");
				return returnMap;
			}
			ok:
			for (int i = 2; i < newRow; i++) {
				for (int j = 1; j < 6; j++) {

					Map<String, Object> resultMap = new HashMap<String, Object>();
					//第一个是列数，第二个是行数
					String questionName = rs.getCell(j++, i).getContents().trim();
					String type = rs.getCell(j++, i).getContents().trim();//默认最左边编号也算一列 所以这里得j++
					String optionMsg = rs.getCell(j++, i).getContents().trim();
					String ansquesContent = rs.getCell(j++, i).getContents().trim();
					String courseName = rs.getCell(j++, i).getContents().trim();
					logger.info("type" + type);
					questionName = PubMethods.isStr(questionName);
					optionMsg = PubMethods.isStr(optionMsg);

					if (questionName.equals("") || questionName == null) {
						returnMap.put("list", null);
						returnMap.put("errMsg", "题目不可为空，导入失败");
						break ok;
					}
					if (questionName.length() > 500) {
						returnMap.put("list", null);
						returnMap.put("errMsg", "题目字数请限制在100字以内，导入失败");
						break ok;
					}
					if (courseName.equals("") || courseName == null) {
						returnMap.put("list", null);
						returnMap.put("errMsg", "课程名不可为空，导入失败");
						break ok;
					}
					if (ansquesContent.equals("") || ansquesContent == null) {
						returnMap.put("list", null);
						returnMap.put("errMsg", "答案不可为空，导入失败");
						break ok;
					}

				/*	if(!optionMsg.equals("")&&optionMsg!=null){
						optionMsg = optionMsg.replaceAll("\n", "<br>");
						optionMsg = optionMsg.replaceAll("\r", "<br>");
					}*/

					ansquesContent = ansquesContent.replaceAll("\n", "<br>");
					ansquesContent = ansquesContent.replaceAll("\r", "<br>");

					//通过questionName查询数据库是否应经存在此试题
					Map<String, Object> paraMap = new HashMap<String, Object>();
					paraMap.put("questionName", questionName);

					if (type.equals("单选")||type.equals("多选") || type.equals("判断") || type.equals("填空") || type.equals("简答")) {
						if (type.equals("单选")) {
							questionType = 1;
						}
						if (type.equals("判断")) {
							questionType = 2;
						}
						if (type.equals("填空")) {
							questionType = 3;
						}
						if (type.equals("简答")) {
							questionType = 4;
						}
						if (type.equals("多选")) {
							questionType = 5;
						}
						if (optionMsg == null || optionMsg.equals("")) {
							optionMsg = "";
						}
						//判断题目输入格式是否正确
						Map<String,Object> isBraMap = new HashMap<String, Object>();
						isBraMap.put("questionName",questionName);
						isBraMap.put("optionMsg",optionMsg);
						isBraMap.put("ansquesContent",ansquesContent);
						isBraMap.put("questionType",questionType);
						Map<String,Object> isBrMap =  PubMethods.isBrackets(isBraMap);
						if(!(Boolean)isBrMap.get("flag")){
							returnMap.put("list", null);
							returnMap.put("errMsg", "第"+(i+1)+"行"+isBrMap.get("msg"));
							break ok;
						}
						//通过课程名查询课程id
						Map<String, Object> paramMap = new HashMap<String, Object>();
						logger.info("courseName" + courseName);
						paramMap.put("courseName", courseName);
						Map<String, Object> courseMap = courseDao.getCourseDetailByName(paramMap);
						int courseId = 0;
						if (courseMap != null) {
							courseId = Integer.valueOf(String.valueOf(courseMap.get("courseId")));
							Map<String, Object> newMap = new HashMap<String, Object>();
							newMap.put("courseId", courseId);
							newMap.put("stuorteaId", stuorteaId);
							//查询某课程是否属于当前教师（20180308改，如果以后出问题在改）
						   newMap.put("isMark", 0);//要获取当前教师拥有的课（包括教师录入和教的）
						   List<Map<String, Object>> exitList = courseDao.getExitCourseByTeaId(newMap);
							//20180308 商莹改  通过教师号获取此教师所属课程（教的）
//							paramMap.put("stuorteaId",stuorteaId);
//							List<Map<String,Object>> exitList = courseDao.getTeaOwenCourse(paramMap);
							if (exitList.size() == 0) {
								//说明要导入的试题科目不属于当前教师，提示不可以导入
								list = null;
								returnMap.put("list", list);
								returnMap.put("errMsg", "当前教师没有此课程，导入失败");
								break ok;
							}
							paraMap.put("courseId",courseId);
							List<Map<String,Object>> questionMap = questionDao.getQuestionByName(paraMap);
							if (questionMap != null && questionMap.size() != 0) {
								returnMap.put("list", null);
								returnMap.put("errMsg","第"+(i+1)+"行题目重复请检查数据，导入失败");
								break ok;
							}
							resultMap.put("questionName", questionName);
							resultMap.put("questionType", questionType);
							resultMap.put("optionMsg", optionMsg);
							resultMap.put("ansquesContent", ansquesContent);
							resultMap.put("courseId", courseId);
							list.add(resultMap);
							returnMap.put("list", list);
						} else {
							list = null;
							returnMap.put("list", list);
							returnMap.put("errMsg", "所填课程不存在");
							break ok;
						}
					} else {
						//说明填写数据不正确
						list = null;
						returnMap.put("list", list);
						returnMap.put("errMsg", "第"+(i+1)+"行所填问题类型不正确");
						break ok;
					}

				}
			}
			if(returnMap.get("list")!=null){
				//判断导入试题中是否存在重复数据
				List<Map<String, Object>> listAll = (List<Map<String, Object>>)returnMap.get("list");
				for  ( int  i  =   0 ; i  <  listAll.size()  -   1 ; i ++ )  {
					for  ( int  j  =  listAll.size()  -   1 ; j  >  i; j -- )  {
						if  (String.valueOf(listAll.get(j).get("questionName")).equals(String.valueOf(listAll.get(i).get("questionName"))))  {
							//说明有重复数据
							returnMap.put("list", null);
							returnMap.put("errMsg", "题目重复请检查数据，导入失败");
						}
					}
				}
			}
		} catch (Exception e) {

			e.printStackTrace();
		}
		return returnMap;
	}

	/**
	 * 在线预览表单提交
	 * param:mark 1添加  2修改  onlinequestionId试卷主键id  添加时给我0修改时给我正常主键
	 * randomMark 1重新随机生成试题（修改时记录数据库）  2不重新随机生成试题（修改时记录数据库）(添加时不用给我或者给我0都可以)
	 * fileName 试卷名
	 * @throws IOException
	 */
	public Map<String,Object> addOnlineQuestion(Map<String,Object> paramMap, HttpServletRequest request) throws Exception {

		boolean flag = false;
		Map<String,Object> returnMap = new HashMap<String, Object>();
		String str="";
		String fileName =String.valueOf(paramMap.get("fileName"));
		try {
			//获取当前登陆人的工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId")) ;
			paramMap.put("stuorteaId", stuorteaId);
			paramMap.put("teaId", stuorteaId);
			//通过文件名查onlinequestion
			if(!String.valueOf(paramMap.get("fileName")).contains(".doc")){
				fileName = fileName +".doc";
			}
			paramMap.put("fileName",fileName);
			Map<String,Object> queMap=questionDao.getOnlineQuestionByFileName(paramMap);
			if(queMap!=null){
				returnMap.put("flag",false);
				returnMap.put("str","试卷名称已存在");
				return returnMap;
			}


			//将paperDetailMap这个对象转换成字符串
			Map<String,Object> paperDetailMap = getPaperDetail(paramMap);
			String paperDetail = String.valueOf(paperDetailMap.get("paperDetail")) ;
			paramMap.put("paperDetail",paperDetail);
			paramMap.put("onlineSumSource",paperDetailMap.get("onlineSumSource"));
			if(Integer.parseInt(String.valueOf(paramMap.get("mark")))==1){
				//添加
				flag = questionDao.addOnlineQuestion(paramMap);
				//查询当前教师、当前课程，教师与班级的关联集合
				List<Map<String,Object>> classList = relStuClassDao.getClassByTeaIdAndCoId(paramMap);
				if(classList!=null&&classList.size()!=0){
					//通过新添加的主键id查询试卷信息
					int onlinequestionId = Integer.parseInt(String.valueOf(paramMap.get("onlinequestionId")));
					paramMap.put("onlinequestionId",onlinequestionId);
					Map<String,Object> questionMap = questionDao.getStartTimeByOnId(paramMap);
					questionMap.put("classList",classList);
					questionMap.put("mark",1);//标识用哪个sql
					questionMap.put("onlinequestionId",onlinequestionId);
					//复制添加的试卷,形成每个班级对应一份试卷
					questionDao.addCopyOnlineQuestion(questionMap);

					//将复制好的试卷与班级的关联加入关联表中
					questionMap.put("mark",2);
					List<Map<String,Object>> list = new ArrayList<>();
					list.add(paramMap);
					questionMap.put("list",list);
					List<Map<String,Object>> copyList = questionDao.getAllCopyQuIdList(questionMap);
					questionMap.put("copyList",copyList);
					//查询要复制试卷对应的班级是否已经考过试(同一课程)
					List<Map<String,Object>> copyAreadyExamClassList = questionDao.getAllArealdyExamCopyClassList(questionMap);
					//将copyList与copyAreadyExamClassList合并
					copyList = getCoypList(copyList,copyAreadyExamClassList);
					questionDao.addreClassOnlineByListId(questionMap);
			}
			}else{
				//通过主键id查询当前老师当前试卷是否开始考试
				List<String> list = new ArrayList<>();
				list.add(String.valueOf(paramMap.get("onlinequestionId")));
				List<Map<String,Object>> quList = questionDao.getAllFileNameListById(list);
				if(Integer.parseInt(String.valueOf(quList.get(0).get("examState")))==1){
					//说明已经开始考试，不可在修改
					returnMap.put("flag",false);
					returnMap.put("str","已经开始考试，不可修改");
					return returnMap;
				}else{
					if(Integer.valueOf(String.valueOf(paramMap.get("randomMark")))==1){
						//修改且所有内容都有修改
						flag = questionDao.updateOnlineQuestion(paramMap);
						//修改此试卷对应所有复制的试卷
						flag = questionDao.updateCopyOnlineQuestion(paramMap);
					}if(Integer.valueOf(String.valueOf(paramMap.get("randomMark")))==2){
						//修改且只有试卷名和考试时间可以修改
						flag = questionDao.updateOnlineQuestionOnly(paramMap);
						//修改此试卷对应所有复制的试卷只有试卷名和考试时间可以修改
						flag = questionDao.updateCopyOnlineQuestionOnly(paramMap);
					}
				}
			}
			if(flag&&Integer.valueOf(String.valueOf(paramMap.get("randomMark")))!=2){
				String[] keysArray = {"tomcatUrl", "project_name","server_address"};
				Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
				//判断文件夹存不存在,不存在就创建
				String path = String.valueOf(urlmap.get("tomcatUrl"))+String.valueOf(urlmap.get("project_name"))+"upload/question"+"/"+fileName;
				File saveFile = new File(path);
				if (!saveFile.exists()) {
					String s = path.substring(0,path.lastIndexOf("/") + 1);
					File saveFileDir = new File(s);
					saveFileDir.mkdirs();
					saveFile = new File(path);
				}
				//试卷生成word文档保存到服务器
				Map<String,Object> resultMap = this.getAllQuestionListExcel(paramMap,request);
				ITextWord iword = ITextWord.getInstance();
				FileOutputStream out = new FileOutputStream(path);
				if(resultMap!=null){
					logger.info("生成试题的resultMap不为空"+resultMap);
					resultMap.put("fileName",fileName);

					iword.createRtfContext(resultMap,out,"word",paramMap);
					out.flush();
					out.close();
					flag = true;

				}else{
					logger.info("当前课程在题库中没有相应的试题，生成试题失败"+resultMap);
					flag = false;
					str = "当前课程在题库中没有相应的试题，保存失败";
				}
			}
			returnMap.put("flag",flag);
			returnMap.put("str",str);

		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	private List<Map<String,Object>> getCoypList(List<Map<String,Object>> copyList,List<Map<String,Object>> copyAreadyExamClassList){
		//将copyList与copyAreadyExamClassList合并
		for(int i=0;i<copyList.size();i++){
			copyList.get(i).put("classExamState",0);
			for (int j=0;j<copyAreadyExamClassList.size();j++){
				if(Integer.parseInt(String.valueOf(copyList.get(i).get("classId")))==Integer.parseInt(String.valueOf(copyAreadyExamClassList.get(j).get("classId")))){
					copyList.get(i).put("classExamState",copyAreadyExamClassList.get(j).get("classExamState"));
					break;
				}
			}
		}
		return copyList;
	}

	//重新组合paperDetailMap
	private Map<String,Object> getPaperDetail(Map<String,Object> paramMap){
		Map<String,Object> returnMap = new HashMap<>();
		//将前台传过来的题数量和分数解析成map对象
		String paperDetail = String.valueOf(paramMap.get("paperDetail"));
		Map<String,Object> paperDetailMap =  JSONObject.parseObject(paperDetail);
		int answerPageSize = Integer.parseInt(String.valueOf(paperDetailMap.get("answerPageSize")));
		int judgePSize = Integer.parseInt(String.valueOf(paperDetailMap.get("judgePSize")));
		int manyOptionPageSize = Integer.parseInt(String.valueOf(paperDetailMap.get("manyOptionPageSize")));
		int optionPageSize = Integer.parseInt(String.valueOf(paperDetailMap.get("optionPageSize")));
		int blanksPageSize = Integer.parseInt(String.valueOf(paperDetailMap.get("blanksPageSize")));

		int blankssource = Integer.parseInt(String.valueOf(paramMap.get("blankssource")));
		int judgesource = Integer.parseInt(String.valueOf(paramMap.get("judgesource")));
		int manyOptionSorce = Integer.parseInt(String.valueOf(paramMap.get("manyOptionSorce")));
		int optionsource = Integer.parseInt(String.valueOf(paramMap.get("optionsource")));
		int answersource = Integer.parseInt(String.valueOf(paramMap.get("answersource")));
		//查询所要生成的试题的数量是否符合要求
		Map<String, Object> listMap = getListMap(paramMap);
		List<Map<String, Object>> optionList = (List<Map<String, Object>>) listMap.get("optionList");
		List<Map<String, Object>> manyOptionList = (List<Map<String, Object>>) listMap.get("manyOptionList");
		List<Map<String, Object>> judgeList = (List<Map<String, Object>>) listMap.get("judgeList");
		List<Map<String, Object>> blanksList = (List<Map<String, Object>>) listMap.get("blanksList");
		List<Map<String, Object>> answerList =(List<Map<String, Object>>) listMap.get("answerList");
		if(answerPageSize!=0&&answerPageSize>answerList.size()){
			answerPageSize = answerList.size();
		}if(answerPageSize==0){
			answersource = 0;
			paperDetailMap.put("answersource",answersource);
		}
		if(judgePSize!=0&&judgePSize>judgeList.size()){
			judgePSize = judgeList.size();
		}if(judgePSize==0){
			judgesource = 0;
			paperDetailMap.put("judgesource",judgesource);
		}
		if(manyOptionPageSize!=0&&manyOptionPageSize>manyOptionList.size()){
			manyOptionPageSize = manyOptionList.size();
		}if(manyOptionPageSize==0){
			manyOptionSorce = 0;
			paperDetailMap.put("manyOptionSorce",manyOptionSorce);
		}
		if(optionPageSize!=0&&optionPageSize>optionList.size()){
			optionPageSize = optionList.size();
		}if(optionPageSize==0){
			optionsource = 0;
			paperDetailMap.put("optionsource",optionsource);
		}
		if(blanksPageSize!=0&&blanksPageSize>blanksList.size()){
			blanksPageSize = blanksList.size();
		}if(blanksPageSize==0){
			blankssource = 0;
			paperDetailMap.put("blankssource",blankssource);
		}
		//将paperDetail重新组合
		paperDetailMap.put("blanksPageSize",blanksPageSize);
		paperDetailMap.put("optionPageSize",optionPageSize);
		paperDetailMap.put("manyOptionPageSize",manyOptionPageSize);
		paperDetailMap.put("judgePSize",judgePSize);
		paperDetailMap.put("answerPageSize",answerPageSize);
		paperDetail = JSONObject.toJSONString(paperDetailMap);
		returnMap.put("paperDetail",paperDetail);
		double onlineSumSource = (blanksPageSize*blankssource)+(optionPageSize*optionsource)+(manyOptionPageSize*manyOptionSorce)+(judgePSize*judgesource)+(answerPageSize*answersource);
		returnMap.put("onlineSumSource",onlineSumSource);
		return returnMap;
	}

	/**
	 * @param courseid,stuorteaid
	 * @return  通过课程id和当前登陆人所属老师的工号查询当前课程的试题
	 * @throws IOException
	 */
	public Map<String, Object> getOnlineQuestion(Map<String, Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			returnMap.put("stuorteaId", stuorteaId);
			paramMap.put("stuorteaId", stuorteaId);

			//通过学生获取此学生所属课程
			List<Map<String,Object>> courseList = myCourseDao.getStuCourse(paramMap);
			//通过学号查询所属教师
			List<Map<String,Object>> teaList = relationDao.getMyTeacherByCourseId (paramMap);
			//通过学号和课程号获取此学生所属老师，查出当前科目当前老师生成的试题
			if(teaList!=null&&teaList.size()!=0){
				paramMap.put("teaId", teaList.get(0).get("stuorteaId"));
				paramMap.put("classId", teaList.get(0).get("classId"));
				Map<String,Object> questonMap = questionDao.getOnlineQuestion(paramMap);
				if (Integer.parseInt(String.valueOf(questonMap.get("examState"))) == 0) {
					returnMap.put("flag",false);
					returnMap.put("errMsg", "此课程还没开始考试");
					returnMap.put("questonMap", null);
					returnMap.put("courseList", courseList);
					return returnMap;
				}
				//查询当前学生是否已经答过题
				paramMap.put("onlinequestionId",questonMap.get("onlinequestionId"));
				Map<String,Object> stuquMap = questionDao.getStuAnswerByOnIdAndCouId(paramMap);
				if(stuquMap!=null){
					//已经答过题 提示已提交过试卷不可重复提交
					returnMap.put("flag", false);
					returnMap.put("errMsg", "已提交过试卷不可重复提交");
					returnMap.put("questonMap", null);
					returnMap.put("courseList", courseList);
					return returnMap;
//				flag = questionDao.updateStuAnswerQuestion(paramMap);
				}
				if(questonMap!=null&&questonMap.size()!=0){
					//查询教师点击考试的时间
//					Map<String,Object> onlineMap = questionDao.getStartTimeByOnId(paramMap);
					String endTime = String.valueOf(questonMap.get("endTime"));
					double mincha = PubMethods.surplusTime(endTime);//（考试结束时间-当前时间=时间差）
					mincha = mincha*60;
					if(mincha<0){
						mincha=0;
					}
					//通过学生Id和onlinequestionId查询学生自动保存的信息
					Map<String,Object> saveMap = questionDao.getStuOnlineInfoById(paramMap);
					String saveInfo = "";
					List<Map<String,Object>> answerList = new ArrayList<>();
					if(saveMap!=null&&saveMap.size()!=0){
						saveInfo = String.valueOf(saveMap.get("saveInfo"));
						answerList = (List<Map<String, Object>>) JSONObject.parse(saveInfo);
						questonMap.put("answerList",answerList);
					}else{
						questonMap.put("answerList",null);
					}
					returnMap.put("questonMap", questonMap);
					returnMap.put("courseList", courseList);
					returnMap.put("mincha", mincha);
					returnMap.put("flag", true);
					returnMap.put("errMsg", "生成试题成功");
				}else{
					//说明此教师没有课程
					returnMap.put("flag", false);
					returnMap.put("errMsg", "当前课程没有试题");
					return returnMap;
				}
			}else{
				//说明此学生没有所属教师
				returnMap.put("flag", false);
				returnMap.put("errMsg", "当前学生没有所属教师");
				return returnMap;
			}


		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * 学生在线考试表单提交
	 * @throws IOException
	 */
	public synchronized Map<String,Object>  addStuAnswerQuestion(Map<String,Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {

		boolean flag = false;
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		Map<String,Object> returnMap = new HashMap<String,Object>();
		String textjson = "";
		String errStr = "";
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//选择题错误个数
		int opworcount = 0;
		//多选选择题错误个数
		int manyOpworcount = 0;
		//判断题错误个数
		int judworcount = 0;
		//单选选择题总分数
		BigDecimal optionallsource = new BigDecimal(0);
		//多选选择题总分数
		BigDecimal manyOptionallsource = new BigDecimal(0);
		//判断题总分数
		BigDecimal judgeallsource = new BigDecimal(0);
		//错误题集合
		List<Integer> errList = new ArrayList<Integer>();
		//错误信息
		String msg = "";
		try {

			//获取当前登陆人的学号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId","realRoleId","userName"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId")) ;
			paramMap.put("stuorteaId", stuorteaId);

			//查询当前学生是否已经答过题
			Map<String,Object> stuquMap = questionDao.getStuAnswerByOnIdAndCouId(paramMap);
			if(stuquMap!=null){
				//已经答过题 提示已提交过试卷不可重复提交
				flag = false;
				msg = "已提交过试卷不可重复提交";
				returnMap.put("flag", flag);
				returnMap.put("msg", msg);
				return returnMap;
			}
			list = (List<Map<String, Object>>) paramMap.get("mapList");
			if(list.size()!=0){
				//通过问题主键查询question表查每道题的正确答案
				List<Map<String,Object>> questonList =  questionDao.getAllQuestionListById(list);
				//计算选择、判断错误个数和得分情况
				Map<String,Object> coutMap = this.coutMethod(questonList,list,paramMap);
				//将前台给的学生答案集合每个做空格、回车处理
				for(int j=0;j<list.size();j++){
					if(String.valueOf(list.get(j).get("ansquesContent"))!=null){
						String ansquesContent = String.valueOf(list.get(j).get("ansquesContent")).replaceAll("\n", "<br>");
						ansquesContent = String.valueOf(list.get(j).get("ansquesContent")).replaceAll("\r", "<br>");
						list.get(j).put("ansquesContent", ansquesContent);
					}
				}
				opworcount = Integer.valueOf(String.valueOf(coutMap.get("opworcount")));
				judworcount = Integer.valueOf(String.valueOf(coutMap.get("judworcount")));
				manyOpworcount = Integer.valueOf(String.valueOf(coutMap.get("manyOpworcount")));
				manyOptionallsource = (BigDecimal) coutMap.get("manyOptionallsource");
				optionallsource = (BigDecimal) coutMap.get("optionallsource");
				judgeallsource = (BigDecimal) coutMap.get("judgeallsource");
				errList = (List<Integer>) coutMap.get("errList");
				paramMap.put("opworcount", opworcount);
				paramMap.put("judworcount", judworcount);
				paramMap.put("manyOpworcount", manyOpworcount);
				paramMap.put("optionallsource", optionallsource);
				paramMap.put("judgeallsource", judgeallsource);
				paramMap.put("manyOptionallsource", manyOptionallsource);
				textjson = mapper.writeValueAsString(list);
				paramMap.put("textjson", textjson);
				errStr = mapper.writeValueAsString(errList);
				paramMap.put("errList", errStr);
			}else{
				//说明教师生成的试题是空卷
				paramMap.put("opworcount", 0);
				paramMap.put("judworcount", 0);
				paramMap.put("manyOpworcount", 0);
				paramMap.put("manyOptionallsource", 0);
				paramMap.put("optionallsource", 0);
				paramMap.put("judgeallsource", 0);
				paramMap.put("textjson", errStr);
				paramMap.put("errList", errStr);
			}
			//添加
			flag = questionDao.addStuAnswerQuestion(paramMap);
			returnMap.put("flag", flag);
			returnMap.put("msg", msg);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * 学生在线考试表单自动保存
	 * @throws IOException
	 */
	public synchronized Map<String,Object>  stuOnlineAutomaticSaveExam(Map<String,Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {

		boolean flag = true;
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		Map<String,Object> returnMap = new HashMap<String,Object>();
		String textjson = "";
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//错误信息
		String msg = "";
		try {
			//获取当前登陆人的学号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId")) ;
			paramMap.put("stuorteaId", stuorteaId);
			list = (List<Map<String, Object>>) paramMap.get("mapList");
			if(list.size()!=0){
				textjson = mapper.writeValueAsString(list);
				paramMap.put("saveInfo", textjson);
				//通过onlinequestionId和stuorteaId查询学生信息是否已经保存
				Map<String,Object> infoMap = questionDao.getStuOnlineInfoById(paramMap);
				if(infoMap!=null&&infoMap.size()!=0){
					//做更新操作
					flag = questionDao.stuUpdateOnlineAutomaticSaveExam(paramMap);
				}else{
					//做添加操作
					flag = questionDao.stuOnlineAutomaticSaveExam(paramMap);
				}
			}
			if(!flag){
				returnMap.put("result", "fail");
				returnMap.put("msg", "保存失败");
				return returnMap;
			}
			returnMap.put("result", "success");
			returnMap.put("msg", msg);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * @param
	 * @return  在线批阅列表
	 * @throws IOException
	 */
	public Map<String, Object> getAllStuExamList(Map<String, Object> paramMap,HttpSession session,HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
//			String stuorteaId = "1210711012";
			returnMap.put("stuorteaId", stuorteaId);
			paramMap.put("stuorteaId", stuorteaId);
			//该教师的当前所属的所有班级学生考试情况(未结课的)
			List<Map<String,Object>> memList = questionDao.getAllStuExamList(paramMap);
			returnMap.put("memList", memList);
			//通过教师号获取此教师所属班级(不要结课的班级---3.0里已经没有结课班级这个说法了（就是教师教的所有班级）)
			List<Map<String,Object>> classList = relStuClassDao.getClassByStuorteaIdAndNo(paramMap);
			returnMap.put("classList", classList);
			//通过教师号获取此教师所属课程(教的--未结课的课程(不带班级，因为带班级的时候会出现重复课程))
			List<Map<String,Object>> courseList = courseDao.getTeaTeachCourseListByNoEndClassId(paramMap);
			returnMap.put("courseList", courseList);
			returnMap.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			List<Map<String, Object>> allMemberList = questionDao.getAllStuExamList(paramMap);
			int totalPage = pageUtil.getTotalPage(allMemberList, pageSize);
			returnMap.put("totalPage", totalPage);

		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * @param
	 * @return   获取试卷基本信息
	 * @throws IOException
	 */
	public Map<String, Object> getOnlineById(Map<String, Object> paramMap) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			returnMap = questionDao.getStartTimeByOnId(paramMap);

		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * @param
	 * @return 通过课程id和学号查询当前课程的试题
	 * @throws IOException
	 */
	public Map<String, Object> getMarkStuQuestion(Map<String, Object> paramMap,HttpSession session ,HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		List<Map<String, Object>> answerList = new ArrayList<Map<String, Object>>();
		List<Integer> errList = new ArrayList<Integer>();
		Map<String,Object> newQuestion = new HashMap<String,Object>();
		ObjectMapper mapper = new ObjectMapper();
		try {
			//获取当前登陆人的工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String teaId = String.valueOf(sessionMap.get("stuorteaId"));
			Map<String, Object> proMap = new HashMap<String, Object>();
			proMap.put("stuorteaId",teaId);
			proMap.put("courseId",paramMap.get("courseId"));
			//判断当前登陆人是否设置了权重
			/*Map<String,Object> sourceMap =  sourceDao.getProWedith(proMap);
			if(sourceMap==null||sourceMap.size()==0){
				//说明当前登陆人没有设置权重
				errMsg = "请设置成绩等级";
				returnMap.put("errMsg",errMsg);
				returnMap.put("question",null);
				return returnMap;
			}*/
			//通过课程id和学号查询当前课程的试题
			Map<String,Object> question = questionDao.getMarkStuQuestion(paramMap);
			String str = String.valueOf(question.get("textjson"));
			if(String.valueOf(question.get("textjson"))!=null&&!String.valueOf(question.get("textjson")).equals("")&&!String.valueOf(question.get("textjson")).equals("null")){
				//取出学生答案解析成对象后传给前台
				String textjson = String.valueOf(question.get("textjson"));
				answerList = mapper.readValue(textjson, answerList.getClass());

			}if(String.valueOf(question.get("errlist"))!=null&&!String.valueOf(question.get("errlist")).equals("")&&!String.valueOf(question.get("errlist")).equals("null")){
				//将错误题集合转换成对象传给前台
				String errstr =  (String) question.get("errlist");
				errList = mapper.readValue(errstr, errList.getClass());
			}

			newQuestion.put("answerList", answerList);
			newQuestion.put("errList", errList);
			newQuestion.put("submitMark",question.get("submitMark"));
			newQuestion.put("optionallsource", question.get("optionallsource"));
			newQuestion.put("judgeallsource", question.get("judgeallsource"));
			newQuestion.put("blankscount", question.get("blankscount"));
			newQuestion.put("answersource", question.get("answersource"));
			newQuestion.put("stuorteaId", question.get("stuorteaId"));
			newQuestion.put("judworcount", question.get("judworcount"));
			newQuestion.put("manyOpworcount", question.get("manyOpworcount"));
			newQuestion.put("manyOptionallsource", question.get("manyOptionallsource"));
			newQuestion.put("state", question.get("state"));
			newQuestion.put("answercount", question.get("answercount"));
			newQuestion.put("courseId", question.get("courseId"));
			newQuestion.put("blanksallsource", question.get("blanksallsource"));
			newQuestion.put("oTestJson", question.get("oTestJson"));
			newQuestion.put("opworcount", question.get("opworcount"));
			newQuestion.put("stuquId", question.get("stuquId"));
			newQuestion.put("courseName", question.get("courseName"));
			newQuestion.put("classId", question.get("classId"));
			newQuestion.put("onlinequestionId", question.get("onlinequestionId"));
			newQuestion.put("onlineSumSource", question.get("onlineSumSource"));
			newQuestion.put("scoreList",question.get("scoreList"));
			returnMap.put("question", newQuestion);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * @param
	 * @return 通过课程id和学号查询当前课程的试题
	 * @throws IOException
	 */
	public Map<String, Object> isSetOnlineExamGrade(Map<String, Object> paramMap,HttpSession session ,HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			//获取当前登陆人的工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String teaId = String.valueOf(sessionMap.get("stuorteaId"));
			Map<String, Object> proMap = new HashMap<String, Object>();
			proMap.put("stuorteaId",teaId);
			proMap.put("courseId",paramMap.get("courseId"));
			//判断当前登陆人是否设置了权重
			Map<String,Object> sourceMap =  sourceDao.getProWedith(proMap);
			if(sourceMap==null||sourceMap.size()==0){
				//说明当前登陆人没有设置权重
				returnMap.put("errMsg","请设置成绩等级");
				returnMap.put("reslult","fail");
				return returnMap;
			}
			returnMap.put("errMsg","");
			returnMap.put("result","success");

		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}


	/**
	 *  评分规则：
	 * 1、查询这个人，这个班级下的平时成绩最高分数
	 2、x = 100/最高分，保留两位小数
	 3、y = 本学生的平时分 *  x
	 4、平时分总分数 =  y * 平时分的权重
	 5、考试成绩总分数 = 本学生的考试成绩 *（1-权重）
	 6、总成绩 = 平时成绩总分数 + 考试成绩总分数
	 *编辑在线考试、编辑成绩表
	 * @throws IOException
	 */
	public Map<String,Object> addExameSource(Map<String,Object> paramMap,HttpSession session, HttpServletRequest request) throws Exception {
		boolean flag = false;
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> sourceMap = new HashMap<String,Object>();
		try {
			if(Integer.parseInt(String.valueOf(paramMap.get("examMark")))==1){
				//说明是计入成绩的
				//批阅教师ID(20171107将批阅人ID存入数据库)
				Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
				String teaId= String.valueOf(sessionMap.get("stuorteaId"));
				paramMap.put("teaId",teaId);
				Map<String,Object> proMap = new HashMap<String,Object>();
				proMap.put("stuorteaId",teaId);
				proMap.put("courseId",paramMap.get("courseId"));
				//查询课程名称
				Map<String,Object> courseDetail= courseDao.getCourseDetail(paramMap);
				//20180720改--将学生答题试卷的html代码和样式生成word文件
				String[] keysArray = {"tomcatUrl", "project_name","server_address"};
				Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
				String path = String.valueOf(urlmap.get("tomcatUrl"))+String.valueOf(urlmap.get("project_name"))+"upload/stuExam/";
				File saveFile = new File(path);
				if (!saveFile.exists()) {
					String s = path.substring(0,path.lastIndexOf("/") + 1);
					File saveFileDir = new File(s);
					saveFileDir.mkdirs();
					saveFile = new File(path);
				}
				String filpathWord = String.valueOf(paramMap.get("stuorteaId"))+"_"+String.valueOf(courseDetail.get("courseName"))+"_"+String.valueOf(paramMap.get("onlinequestionId"))+"_"+"试卷.doc";
				String filePath = path+filpathWord;

			/*String filpathWord = String.valueOf(paramMap.get("stuorteaId"))+String.valueOf(courseDetail.get("courseName"))+"试卷.doc";
			String path = "C://Users/Administrator/Desktop/xxbg/upload/report/";
			String filePath = path+filpathWord;
			*/
				//将试卷名称插入stuanswerquestion表中
				paramMap.put("fileName",filpathWord);
				questionDao.updateFileStuqustion(paramMap);
				//将前台传过来的html解码
				String htmlStr = Escape.unescape(String.valueOf(paramMap.get("htmlStr")));
				PubMethods.coverHtml(htmlStr,String.valueOf(paramMap.get("cssStr")),filePath);
				//查询课堂权重。
				Map<String,Object> sorceMap = sourceDao.getProWedith(proMap);
				if(sorceMap==null||sorceMap.size()==0){
					//说明当前登陆人没有设置权重
					resultMap.put("resultMark","fail" );
					resultMap.put("errMsg","请设置成绩等级" );
					return resultMap;
				}
				paramMap.put("examSource", paramMap.get("examesource"));
				//查询成绩表中的平时成绩
				Map<String,Object> examMap = sourceDao.getExamBySidAndCourseId(paramMap);
				if(examMap!=null){
					//计算该学生的总分数插入到exame表
					sourceMap.put("classId", paramMap.get("classId"));
					sourceMap.put("courseId", paramMap.get("courseId"));
					//平时成绩换算值
					BigDecimal finPromaceSource = sourceActionImpl.proSource(sourceMap, examMap,session,request);
					//考试成绩换算值
					BigDecimal examSource = sourceActionImpl.examSource(sourceMap, paramMap,session,request);
					//学生最后的成绩
					BigDecimal finSumSource = finPromaceSource.add(examSource);
					paramMap.put("examSource", paramMap.get("examesource"));
					paramMap.put("sumSource", finSumSource);
					paramMap.put("finPromaceSource",finPromaceSource);
					paramMap.put("finExamSource",examSource);
					paramMap.put("type",1);
					//编辑成绩表，将学生总成绩、平时成绩换算值、考试成绩换算值插入数据库。
					flag = questionDao.saveQuestionByStuId(paramMap);
					//编辑学生在线考试表，将填空、简答的错误数量和分数插入数据库。
					flag = questionDao.addExameSource(paramMap);
					String resultMark = (flag == true) ? "success" : "fail";
					resultMap.put("resultMark", resultMark);
				}else{
					//说明该学生没有交作业或者作业没有被评价，则只将考试成绩插入成绩表中
					String sId = String.valueOf(paramMap.get("stuorteaId"));
					//考试成绩换算值
					BigDecimal examSource = sourceActionImpl.examSource(paramMap, paramMap,session,request);
					paramMap.put("sumSource", examSource);
					paramMap.put("examSource", paramMap.get("examSource"));
					paramMap.put("finExamSource", examSource);
					paramMap.put("stuorteaId", sId);
					Map<String,Object> map = sourceDao.getExamBySidAndCourseId(paramMap);
					if(map!=null){
						//编辑成绩表，将学生总成绩插入数据库。
						flag = sourceDao.updateSorceBySIdAndMark(paramMap);
					}else{
						//添加成绩表，将学生总成绩插入数据库。
						flag = sourceDao.addExamByMark(paramMap);
					}

					//编辑学生在线考试表，将填空、简答的错误数量和分数插入数据库。
					flag = questionDao.addExameSource(paramMap);
					String resultMark = (flag == true) ? "success" : "fail";
					resultMap.put("resultMark", resultMark);
					resultMap.put("errMsg","");
				}
			}else{
				//说明是不计入成绩的
				resultMap.put("resultMark", "success");
				resultMap.put("errMsg","");
			}


		} catch (Exception e) {
			throw e;
		}
		return resultMap;
	}

	/**
	 * 把is写入到对应的word输出流os中
	 * 不考虑异常的捕获，直接抛出
	 * @param is
	 * @param os
	 * @throws IOException
	 */
	private static void inputStreamToWord(InputStream is, OutputStream os) throws IOException {
		POIFSFileSystem fs = new POIFSFileSystem();
		//对应于org.apache.poi.hdf.extractor.WordDocument
		fs.createDocument(is, "WordDocument");
		fs.writeFilesystem(os);
		os.close();
		is.close();
	}


	/**
	 * 把输入流里面的内容以UTF-8编码当文本取出。
	 * 不考虑异常，直接抛出
	 * @param ises
	 * @return
	 * @throws IOException
	 */
	private static String getContent(InputStream... ises) throws IOException {
		if (ises != null) {
			StringBuilder result = new StringBuilder();
			BufferedReader br;
			String line;
			for (InputStream is : ises) {
				br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				while ((line=br.readLine()) != null) {
					result.append(line);
				}
			}
			return result.toString();
		}
		return null;
	}

	//计算选择、判断错误个数和得分情况
	public Map<String,Object> coutMethod(List<Map<String,Object>> questonList,List<Map<String,Object>> list,Map<String,Object> paramMap){
		//单选选择题错误个数
		int opworcount = 0;
		//多选选择题错误个数
		int manyOpworcount = 0;
		//判断题错误个数
		int judworcount = 0;
		//单选选择题总分数
		BigDecimal optionallsource = new BigDecimal(0);
		//多选选择题总分数
		BigDecimal manyOptionallsource = new BigDecimal(0);
		//判断题总分数
		BigDecimal judgeallsource = new BigDecimal(0);
		//错误题集合
		List<Integer> errList = new ArrayList<Integer>();
		//循环集合计算选择判断错误个数和得分
		for(int i=0;i<questonList.size();i++){
			for(int j=0;j<list.size();j++){
				if(Integer.parseInt(String.valueOf(questonList.get(i).get("questionType")))==1||Integer.parseInt(String.valueOf(questonList.get(i).get("questionType")))==2||Integer.parseInt(String.valueOf(questonList.get(i).get("questionType")))==5){
					if(String.valueOf(list.get(j).get("questionId")).equals(String.valueOf(questonList.get(i).get("questionId")))){
						//判断学生答案是否正确---单选
						if(String.valueOf(list.get(j).get("ansquesContent")).trim().toUpperCase().equals(String.valueOf(questonList.get(i).get("ansquesContent")).trim().toUpperCase())&&(Integer)(questonList.get(i).get("questionType"))==1){
							BigDecimal optionSource = new BigDecimal(String.valueOf(paramMap.get("optionSource")));
							optionallsource = optionallsource.add(optionSource);
						}if(!(String.valueOf(list.get(j).get("ansquesContent")).trim().toUpperCase().equals(String.valueOf(questonList.get(i).get("ansquesContent")).trim().toUpperCase()))&&(Integer)(questonList.get(i).get("questionType"))==1){
							opworcount = opworcount+1;
							//将错误题主键加入到集合中
							int id = Integer.valueOf(String.valueOf(list.get(j).get("questionId")));
							errList.add(id);
						}
						//多选--判断是否答案正确 true不正确 false正确
						if(Integer.parseInt(String.valueOf(questonList.get(i).get("questionType")))==5){
							boolean manyFlag = PubMethods.isManyOptionTure(String.valueOf(list.get(j).get("ansquesContent")).trim().toUpperCase(),String.valueOf(questonList.get(i).get("ansquesContent")).trim().toUpperCase());
							if(!manyFlag){
								BigDecimal optionSource = new BigDecimal(String.valueOf(paramMap.get("manyOptionSource")));
								manyOptionallsource = manyOptionallsource.add(optionSource);
							}if(manyFlag){
								manyOpworcount = manyOpworcount+1;
								//将错误题主键加入到集合中
								int id = Integer.valueOf(String.valueOf(list.get(j).get("questionId")));
								errList.add(id);
							}
						}
						//判断--判断是否答案正确
						if(String.valueOf(list.get(j).get("ansquesContent")).trim().toUpperCase().equals(String.valueOf(questonList.get(i).get("ansquesContent")).trim().toUpperCase())&&Integer.parseInt(String.valueOf(questonList.get(i).get("questionType")))==2){
							BigDecimal judgeSource = new BigDecimal(String.valueOf(paramMap.get("judgeSource")));
							judgeallsource = judgeallsource.add(judgeSource);
						}if(!(String.valueOf(list.get(j).get("ansquesContent")).trim().toUpperCase().equals(String.valueOf(questonList.get(i).get("ansquesContent")).trim().toUpperCase()))&&Integer.parseInt(String.valueOf(questonList.get(i).get("questionType")))==2){
							judworcount = judworcount+1;
							//将错误题主键加入到集合中
							int id = Integer.valueOf(String.valueOf(list.get(j).get("questionId")));
							errList.add(id);
						}
					}
				}
			}
		}
		paramMap.put("errList", errList);
		paramMap.put("optionallsource", optionallsource);
		paramMap.put("opworcount", opworcount);
		paramMap.put("manyOptionallsource", manyOptionallsource);
		paramMap.put("manyOpworcount", manyOpworcount);
		paramMap.put("judgeallsource", judgeallsource);
		paramMap.put("judworcount", judworcount);
		return paramMap;
	}

	//多选--判断是否答案正确 true不正确 false正确
	/*private boolean isManyOptionTure(String str,String str1){
		//如果包含逗号
		str = str.replace(",","");
		str1 = str1.replace(",","");
		if(str==null||str.equals("")){
			return true;
		}
		if(str.length()!=str1.length()){
			return true;
		}
		//目标串中每个字符都包含在原串中
		int length = str.length();
		Map<Character,Integer> targetCount = new HashMap<Character,Integer>();
		for(int i =0;i<length;i++){
			char c = str1.charAt(i);
			//target中某个字符不在原串中，返回false
			int indexOfSource = str.indexOf(c);
			if(indexOfSource==-1){
				return true;
			}

			//统计该串在本串中的个数
			if(targetCount.get(c)==null){
				targetCount.put(c, 1);
			}else{
				Integer count = targetCount.get(c);
				targetCount.put(c, 1+count);
			}
		}

		//统计原串中各个字符的个数
		Map<Character,Integer> sourceCount = new HashMap<Character,Integer>();
		for(int i =0;i<length;i++){
			char c = str.charAt(i);
			if(sourceCount.get(c)==null){
				sourceCount.put(c, 1);
			}else{
				Integer count = sourceCount.get(c);
				sourceCount.put(c, 1+count);
			}
		}

		//目标串中每个字符个数跟原串中对应字符的个数一样
		for(Map.Entry<Character, Integer> entry:targetCount.entrySet()){
			Character key = entry.getKey();
			if(entry.getValue()!=sourceCount.get(key)){
				return true;
			}
		}
		return false;
	}*/

	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  生成试题--获取教师所属课程列表页面。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	public Map<String, Object> getAllCourseListByTeaIdPost(Map<String, Object> paramMap,HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {

			//获取分页数据
			int pageNow = (Integer)paramMap.get("pageNow");
			int pageSize = (Integer)paramMap.get("pageSize");
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
			String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			returnMap.put("stuorteaId", stuorteaId);
			paramMap.put("stuorteaId", stuorteaId);
			//20171030 商莹改  通过教师号获取此教师所属课程（教的）
			List<Map<String,Object>> courseList = courseDao.getTeaOwenCourse(paramMap);
			returnMap.put("courseList", courseList);
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}

	/**
	 * @param request onlinequestionId、courseId
	 * @param response
	 * @return  教师点击开始考试
	 * @throws IOException
	 */
	@Transactional
	public Map<String, Object> updateOnlineState(final Map<String, Object> paramMap, HttpServletRequest request) throws Exception {

		Map<String, Object> returnMap = new HashMap<String, Object>();
		final Map<String,Object> finalMap = paramMap;
		final Map<String,Object> paramMapTwo = paramMap;
		final String[] finalStr = {"fail"};
		try {
			//获取当前登陆人的学号/工号
			Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[]{"stuorteaId"}, request, "userMsg");
			final String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
			paramMap.put("stuorteaId", stuorteaId);
			//查询要考试的班级中是否有状态是正常考试的状态
			List<Map<String,Object>> ifHaveingClass = questionDao.getifHaveingExamingClassList(paramMap);
			if(ifHaveingClass!=null&&ifHaveingClass.size()!=0){
				returnMap.put("resultFlag", false);
				returnMap.put("msg", "有班级正在考试，不可以开始考试");
				return returnMap;
			}
			//查询当前课程学生是否已经考过试并进行操作
			List<Map<String,Object>> arealyList = questionDao.getAealdyExamList(paramMap);
			//查询当前课程当前班级是否已经考试（查这个的目的是因为如果学生没有主动提交试卷，后台自动提交试卷时是延迟一分钟的，如果延迟时间没到，这时候就点击
			// 下一张试卷开始考试，会导致没有将前一张试卷删除，学生登陆在线考试时就会出现脏数据）
			//通过onlinequestionId查询教师设置的考试时间
			List<Map<String,Object>> arealyCourseList = questionDao.getAealdyExamCourseList(paramMap);
			Map<String,Object> questionMap = questionDao.getStartTimeByOnId(paramMap);
			int examtime = Integer.parseInt(String.valueOf(questionMap.get("examtime")));
			//20180814将延迟一分钟提交试卷需求去掉
			//20180815将定时比前台多走5秒
			long millisecond = (examtime*60*1000)+60*1000;
			//计算结束时间用的
			long millsecondEnd = (examtime*60*1000);
			//定时自动交卷
			Timer timer1 = new Timer();
			timer1.schedule(new TimerTask() {
				public void run() {
					try {
						synchronized (this) {
							//通过当前登陆人的id查询其所教学生没有交试卷的人学号集合
							List<Map<String, Object>> stuIdList = relStuClassDao.getStuListNoExam(finalMap);
							if (stuIdList != null && stuIdList.size() != 0) {
								//将没交试卷的学生自动提交试卷（向stuanswerquestion表插入）
								finalMap.put("stuIdList", stuIdList);
								questionDao.addNoExamStuAnswerQuestion(finalMap);
								//编辑成绩表，将学生考试成绩换算值插入数据库。
								automationAddExam(stuIdList, paramMap);
								//查询课程名称
								Map<String,Object> courseDetail= courseDao.getCourseDetail(paramMap);
								//20180720改--将学生答题试卷的html代码和样式生成word文件
								String[] keysArray = {"tomcatUrl", "project_name","server_address"};
								Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
								String path = String.valueOf(urlmap.get("tomcatUrl"))+String.valueOf(urlmap.get("project_name"))+"upload/stuExam/";
								/*String filpathWord = String.valueOf(paramMap.get("stuorteaId"))+String.valueOf(courseDetail.get("courseName"))+"试卷.doc";
								String path = "C://Users/Administrator/Desktop/xxbg/upload/report/";
								String filePath = path+filpathWord;*/
								File saveFile = new File(path);
								if (!saveFile.exists()) {
									String s = path.substring(0,path.lastIndexOf("/") + 1);
									File saveFileDir = new File(s);
									saveFileDir.mkdirs();
									saveFile = new File(path);
								}
								String filpathWord = "";
								String filePath = "";
								for(int i=0;i<stuIdList.size();i++){
									filpathWord = String.valueOf(stuIdList.get(i).get("stuorteaId"))+"_"+String.valueOf(courseDetail.get("courseName"))+"_"+String.valueOf(stuIdList.get(i).get("onlinequestionId"))+"_"+"试卷.doc";
									filePath = path+filpathWord;
									//将试卷名称插入stuanswerquestion表中
									stuIdList.get(i).put("fileName",filpathWord);
									questionDao.updateFileStuqustion(stuIdList.get(i));

									/*Map<String,Object> qMap = questionDao.getStartTimeByOnId(stuIdList.get(i));
									String textjson = String.valueOf(qMap.get("textjson"));
									//解码
									textjson = Escape.unescape(textjson);*/
									PubMethods.coverHtml("","",filePath);
								}
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			}, millisecond);// 设定指定的时间time,此处为2000毫秒

			//定时更改考试状态
			Timer timer = new Timer();
			timer.schedule(new TimerTask() {
				public void run() {
					try {
						synchronized (this) {
							//通过当前登陆人的id查询其所教学生没有交试卷的人学号集合
							/*List<Map<String, Object>> stuIdList = relStuClassDao.getStuListNoExam(finalMap);
							if (stuIdList != null && stuIdList.size() != 0) {
								//将没交试卷的学生自动提交试卷（向stuanswerquestion表插入）
								finalMap.put("stuIdList", stuIdList);
								questionDao.addNoExamStuAnswerQuestion(finalMap);
								//编辑成绩表，将学生考试成绩换算值插入数据库。
								automationAddExam(stuIdList, paramMap);
							}*/
							//修改班级的考试状态，将考试中变成已考试
							paramMapTwo.put("examMark", 1);
							paramMapTwo.put("isEnd", 1);
							paramMapTwo.put("classExamState", 1);
							paramMapTwo.put("list", paramMap.get("list"));
							questionDao.updatereClassOnline(paramMapTwo);
							//将其他班级状态变为已考试
							paramMap.put("classExamState", 1);
							paramMap.put("stuorteaId", stuorteaId);
							updateSecondClassState(paramMap);
							finalStr[0] = "success";
						}
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			}, millsecondEnd);// 设定指定的时间time,此处为2000毫秒

			if(finalStr[0].equals("success")){
				//说明已经进入定时了，也要判断这个科目是否已经考过试了
				arealyExam(arealyList,paramMap,arealyCourseList);
			}
			//元试卷的id
			int onlinequestionId = Integer.valueOf(String.valueOf(paramMap.get("onlinequestionId")));
			paramMapTwo.put("onlinequestionId",paramMap.get("onlinequestionId"));
			//修改元试卷的考试状态
			boolean flag = questionDao.updateOnlineState(paramMap);
			//修改被复制试卷的考试状态
			flag  = questionDao.updateCopyOnlineState(paramMap);
			//将班级的考试状态变为考试中
//			paramMap.put("classExamState",2);saveQuestionByStuId
//			questionDao.updatereClassOnlineState(paramMap);
			String endTime = null;
			if(flag) {
				//通过onlinequestionId查询教师设置的考试时间
				String startTime = String.valueOf(paramMap.get("starttime"));
				//将字符串转成成毫秒数
				long longStartTime = PubMethods.secondTime(startTime);
				if(longStartTime!=0){
					long findalTime = longStartTime+millsecondEnd;
					//将毫秒数转换成字符串
					endTime = PubMethods.getTime(findalTime);
				}
				paramMap.put("endTime",endTime);
				//查询考试班级是否已经插入到关联表中
				List<Map<String, Object>> reOnlineList = questionDao.getreClassOnlineStateByCourseId(paramMap);
				if (reOnlineList != null && reOnlineList.size() != 0) {
					//将考试班级状态更新
					questionDao.updateManyClassOnline(paramMap);
					//查询当前班级状态变为考试中
					paramMap.put("classExamState",2);
					updateSecondClassState(paramMap);
				} else {
					//先删除onlinequestionId为0的（说明为0的数据是添加班级时加的关联，不是点击考试加的关联，所以先删除在增加）
					paramMap.put("onlinequestionId", 0);
					questionDao.delreClassOnlineByOnId(paramMap);
					//将考试班级插入数据库
					paramMapTwo.put("onlinequestionId",onlinequestionId);
					paramMapTwo.put("endTime",endTime);
					paramMapTwo.put("examState",1);//当前试卷当前班级当前课程的试卷状态
					questionDao.addreClassOnline(paramMapTwo);
				}
				//查询当前课程学生是否已经考过试并进行操作
				arealyExam(arealyList,paramMap,arealyCourseList);
				returnMap.put("resultFlag", flag);
				returnMap.put("msg", "");
			}
		} catch (Exception e) {
			throw e;
		}
		return returnMap;
	}


	//循环将自动提交试卷的学生成绩插入成绩表中
	public void automationAddExam(List<Map<String,Object>> stuIdList,Map<String,Object> paramMap) throws Exception {
		paramMap.put("examSource", 0);
		paramMap.put("finExamSource",0);
		paramMap.put("automaticMark",1);
		for(int i=0;i<stuIdList.size();i++){
			paramMap.put("stuorteaId",stuIdList.get(i).get("stuorteaId"));
			Map<String,Object> map = sourceDao.getExamBySidAndCourseId(paramMap);
			if(map!=null){
				//编辑成绩表，将学生总成绩插入数据库。
				sourceDao.updateSorceBySIdAndMark(paramMap);
			}else{
				//添加成绩表，将学生总成绩插入数据库。
				paramMap.put("sumSource",0);
				sourceDao.addExamByMark(paramMap);
			}
		}
	}

	//查询当前班级状态时考试中的集合,并将更改班级状态
	public void updateSecondClassState(Map<String,Object> paramMap){
		try {
			//查询当前班级状态是考试中的集合
			List<Map<String,Object>> classList = (List<Map<String, Object>>) paramMap.get("list");
			if(classList!=null&&classList.size()!=0){
				//将这些班级的其他试卷中班级的状态改为考试中
				paramMap.put("classList",classList);
				questionDao.updateClassState(paramMap);
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	//查询当前课程学生是否已经考过试并进行操作
	private void arealyExam(List<Map<String,Object>> arealyList,Map<String,Object> map,List<Map<String,Object>> arealyCourseList){
		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("courseId",map.get("courseId"));
		paramMap.put("onlinequestionId",map.get("onlinequestionId"));
		try {
			if(arealyList!=null&&arealyList.size()!=0){
				//有可能考试的班级人全给删除了，所以没查出来结果，这个时候需要将已考试的试卷替换掉
				//通过班级id查询班级是否没人
				List<Map<String,Object>> classList = (List<Map<String, Object>>) map.get("list");
				for (int i=0;i<classList.size();i++){
					if(Integer.parseInt(String.valueOf(classList.get(i).get("examMark")))!=0){
						//说明是考试的班级，查询这个班级是否有人
						paramMap.put("classId",classList.get(i).get("classId"));
						List<Map<String,Object>> studentList = relStuClassDao.getClassHaveStudent(paramMap);
						if(studentList==null||studentList.size()==0){
							//说明试卷已经考过了，只是学生删除了，所以关联没有了所以上面的集合没有值，这时我们需要前一张试卷替换掉
							//查询要被覆盖的试卷集合
							List<Map<String,Object>> onlinequestionList = questionDao.getRequireRepatOnlinequestionList(paramMap);
							if(onlinequestionList!=null &&onlinequestionList.size()!=0){
								paramMap.put("list",onlinequestionList);
								//将前一张试卷变为被替换状态
								questionDao.updatOnlineRepatMark(paramMap);
							}
						}else{
							//说明班级有人，则走正常的
							//说明当前课程已经有学生提交过试卷，现在教师又将另一张试卷开始考试，则需要将前一张试卷学生提交过的试卷删除
							questionDao.delStuanswerByOnlineQuestionId(arealyList);
							//将对应学生的考试成绩和总成绩清空
							paramMap.put("list",arealyList);
							questionDao.clearExamSource(paramMap);
							//将前一张试卷变为被替换状态
							questionDao.updatOnlineRepatMark(paramMap);
						}
					}
				}
			}else{
				/**说明定时还没走，后台给学生还没有提交试卷，所以这只需要将已经考试的试卷替换掉**/
				//将前一张试卷变为被替换状态
				paramMap.put("list",arealyCourseList);
				questionDao.updatOnlineRepatMark(paramMap);
			}


		}catch (Exception e) {
			e.printStackTrace();
		}

	}
}

